package com.yungui.libary.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.yungui.libary.annotation.PassToken;
import com.yungui.libary.annotation.UserLoginToken;
import com.yungui.libary.entity.User;
import com.yungui.libary.exception.BusinessException;
import com.yungui.libary.handler.BlockHandler;
import com.yungui.libary.service.TokenService;
import com.yungui.libary.service.UserService;
import com.yungui.libary.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class UserApiController {
    @Autowired
    UserService userService;
    @Autowired
    TokenService tokenService;
    //登录
    @PostMapping("/login")
    public Object login(@RequestBody User user){
        JSONObject jsonObject=new JSONObject();
        User userForBase=userService.findByUserName(user);
        if(userForBase==null){
            throw new BusinessException("登录失败,用户不存在");
        }else {
            if (!userForBase.getPassword().equals(user.getPassword())){
                throw new BusinessException("登录失败,密码错误");
            }else {
                String token = tokenService.getAccessToken(userForBase);
                String refreshToken = tokenService.getRefreshToken(userForBase);
                jsonObject.put("access_token", token);
                jsonObject.put("refresh_token",refreshToken);
                jsonObject.put("user", userForBase);
                return jsonObject;
            }
        }
    }
    //续签
    @PostMapping("/refresh/token")
    public Object refreshToken(String refreshToken){
        JSONObject jsonObject=new JSONObject();
        User user = new User();
        Long userId = JwtUtil.getUserId(refreshToken);
        user.setId(userId);
        String token = tokenService.getAccessToken(user);
        jsonObject.put("access_token", token);
        return jsonObject;
    }

    @UserLoginToken
    @GetMapping("/getMessage")
    @SentinelResource(value = "libary-app.getMessage",blockHandlerClass = BlockHandler.class,blockHandler = "handleMessage")
    public Object getMessage(){
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("code","000");
        jsonObject.put("message","ok");
        jsonObject.put("data", Lists.newArrayList("中国","日本","英国","美国"));
        return jsonObject;
    }
}